package org.openfans.web;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.openfans.domain.Facade;
import org.openfans.domain.Fans;
import org.openfans.util.ThreadFans;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class FansIconUploadController extends SimpleFormController {
	private Facade facade = null;

	public void setFacade(Facade facade) {
		this.facade = facade;
	}

	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws ServletException {
		binder.registerCustomEditor(byte[].class,
				new ByteArrayMultipartFileEditor());
	}

	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws ServletException, IOException {
		FileUpload bean = (FileUpload) command;
		byte[] bytes = bean.getFile();
		String uploadDir = getServletContext().getRealPath("/upload/");
		String sep = System.getProperty("file.separator");

		Fans fans = ThreadFans.get();
		String fansId = String.valueOf(fans.getFansId());
		String fansImage = fansId + ".gif";
		File uploadedFile = new File(uploadDir + sep + fansImage);
		FileCopyUtils.copy(bytes, uploadedFile);
		// // set success message
		// request.getSession().setAttribute("message", "Upload completed.");
		String icon = request.getContextPath() + "/upload/" + fansImage;
		fans.setIcon(icon);
		facade.save(fans);
		return new ModelAndView(getSuccessView());
	}
}
